#include "sessionfriendarea.h"
#include <QVBoxLayout>
#include <QScrollBar>
#include <Qlabel>
#include <QStyleOption>
#include <QPainter>
#include "debug.h"
#include "model/data.h"
#include "mainWidget.h"
#include "model/datacenter.h"
using namespace  model;


///////////////////////////////////////////////////////////////
/// 滚动区域的实现
///////////////////////////////////////////////////////////////


sessionFriendArea::sessionFriendArea(QWidget *parent)
    : QScrollArea{parent}
{
    //1.设置属性
    //设置滚动属性
    this->setWidgetResizable(true);
    this->verticalScrollBar()->setStyleSheet("width:3px;background-color:rgb(216,216,216);");
    this->horizontalScrollBar()->setStyleSheet("height:0px;");
    this->setObjectName("sessionFriendArea");
    this->setStyleSheet("QWidget#sessionFriendArea{border:1px solid rgb(200,200,200);}");
    //设置滚动条相关的样式

    //2.创建一个widget
    container = new QWidget;
    container->setFixedWidth(310/SCALE);
    this->setWidget(container);


    //3.给这个widget设置一个布局管理器，以便添加元素进去
    QVBoxLayout* layout = new QVBoxLayout;
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);
    layout->setAlignment(Qt::AlignTop);
    container->setLayout(layout);

    //简单测试一下添加会话的滚动效果，后续会使用Item代替
    // for(int i =0;i<30;i++)
    // {
    //     QPushButton* q = new QPushButton;
    //     q->setFixedHeight(100/SCALE);
    //     q->setText("会话"+QString::number(i+1));
    //     layout->addWidget(q);
    // }


    // 构造一些虚假数据来测试UI，调试阶段操作
    #if TEST_UI
    QIcon avatar = QIcon(":/myResource/Image/dogAvatar.svg");
    for(int i=0;i<20;i++)
        this->addItem(ItemType::APPLY,QString::number(i),
                      avatar,"张三","最后的波纹"+QString::number(i));
    #endif
}

void sessionFriendArea::addItem(ItemType type,const QString& id,
                                const QIcon& avatar,const QString& name,const QString& lastMessage)
{
    sessionFriendItem* item;
    switch(type)
    {
    case ItemType::SESSION:
        item = new sessionItem(this,id,avatar,name,lastMessage);
        break;
    case ItemType::FRIEND:
        item = new friendItem(this,id,avatar,name);
        break;
    case ItemType::APPLY:
        item = new applyItem(this,id,avatar,name);
        break;
    default:
        item = nullptr;
        LOG()<<"错误的ItemType:"<<(int)type;
        return;
    }
    container->layout()->addWidget(item);

}
void sessionFriendArea::clickItem(int index)
{
    if(index<0||index>=container->layout()->count())
    {
        LOG()<<"点击的下标超出范围,index:"<<index;
        return;
    }
    QLayoutItem* Item = container->layout()->itemAt(index);
    if(!Item||!Item->widget())
    {
        LOG()<<"指定的元素不存在,index:"<<index;
        return;
    }
    dynamic_cast<sessionFriendItem*>(Item->widget())->beClicked();
}

void sessionFriendArea::clear()
{
    QLayout* layout = container->layout();
    for(int i=layout->count()-1;i>=0;i--)
    {
        QLayoutItem* item =layout->takeAt(i);
        if(item&&item->widget())
        delete item->widget();
    }

}

///////////////////////////////////////////////////////////////
/// 滚动区域中Item的基类
///////////////////////////////////////////////////////////////


sessionFriendItem::sessionFriendItem(QWidget* owner,const QIcon& avatar,const QString& name)
:owner(owner)
{
    this->setFixedHeight(80/SCALE);
    this->setStyleSheet("background-color:rgb(231,231,231);");


    //创建布局管理器
    QGridLayout* layout =new QGridLayout;
    this->setLayout(layout);

    //创建头像
    avatarBtn = new QPushButton;
    avatarBtn->setFixedSize(QSize(50/SCALE,50/SCALE));
    avatarBtn->setIcon(QIcon(avatar));
    avatarBtn->setIconSize(QSize(50/SCALE,50/SCALE));
    avatarBtn->setStyleSheet("QPushButton{border:none;}");
    avatarBtn->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);


    //创建名字
    QLabel* nameLabel = new QLabel;
    nameLabel->setText(name);
    nameLabel->setStyleSheet("QLabel{font-size:14px;font-weight:500;}");
    nameLabel->setFixedHeight(35/SCALE);
    nameLabel->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);

    //布局
    layout->addWidget(avatarBtn,0,0,2,2);
    layout->addWidget(nameLabel,0,2,1,8);

}
void sessionFriendItem::beClicked()
{
    //Item被点下的执行逻辑
    const QObjectList children = this->parent()->children();
    for(auto child:children)
    {
        if(!child->isWidgetType())
            continue;
        auto sfItem =  dynamic_cast<sessionFriendItem*>(child);
        if(sfItem->selected)
        {
            sfItem->selected = false;
            sfItem->setStyleSheet("QWidget{background-color:rgb(231,231,231);}");
            break;
        }
    }
    this->selected = true;
    this->setStyleSheet("QWidget{background-color:rgb(210,210,210);}");
    this->active();

}
void sessionFriendItem::paintEvent(QPaintEvent* event)
{
    (void) event;
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}
void sessionFriendItem::mousePressEvent(QMouseEvent* event)
{
    (void)event;
    beClicked();
}
//鼠标放置颜色略微变深一点
void sessionFriendItem::enterEvent(QEnterEvent* event)
{
    (void)event;
    if(this->selected)
        return;
    this->setStyleSheet("QWidget{background-color:rgb(215,215,215);}");
}
//鼠标离开颜色恢复
void sessionFriendItem::leaveEvent(QEvent* event)
{
    (void)event;
    if(this->selected)
        return;
    this->setStyleSheet("QWidget{background-color:rgb(231,231,231);}");

}
void sessionFriendItem::active()
{
    //这个是被点下后的除颜色外的执行逻辑，需要确保被子类重写，本身不提供执行逻辑
}


///////////////////////////////////////////////////////////////
/// 会话Item
///////////////////////////////////////////////////////////////

sessionItem::sessionItem(QWidget* owner,const QString& sessionId,
                         const QIcon& avatar,const QString& name,const QString& lastMessage)
    :sessionFriendItem(owner,avatar,name),sessionId(sessionId),lastMessage(lastMessage)
{
    messageLabel = new QLabel;
    messageLabel->setText(lastMessage);
    messageLabel->setFixedHeight(20);
    messageLabel->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);
    messageLabel->setStyleSheet("QLabel{font-size:11px;font-weight:100;color:rgb(110,110,110)}");
    dynamic_cast<QGridLayout*>(this->layout())->addWidget(messageLabel,1,2,1,8);

    DataCenter* dataCenter = DataCenter::getInstance();
    connect(dataCenter,&DataCenter::updateLastMessage,this,&sessionItem::updateLastMessage);
    //支持客户端重启后，未读信息正常显示
    int unreadCount = dataCenter->getUnread(sessionId);
    if(unreadCount>0)
        messageLabel->setText(QString("[未读%1条]").arg(unreadCount)+lastMessage);
}
void sessionItem::active()
{
    LOG()<<"会话被点击触发的逻辑，sessionId="<<sessionId;
    //加载会话历史消息(网络获取数据，内存数据更新,页面更新)
    MainWidget* mainWidget = MainWidget::getInstance();
    mainWidget->loadRecentMessage(sessionId);
    DataCenter::getInstance()->clearUnread(sessionId);
    this->messageLabel->setText(lastMessage);

}

void sessionItem::updateLastMessage(const QString &sessionId)
{
    DataCenter* dataCenter = DataCenter::getInstance();
    //1.判断是否是需要更新的会话
    if(sessionId!=this->sessionId)
        return;
    //2.获取最后一条消息
    QList<Message>* msgList = dataCenter->getRecentMessageList(sessionId);
    if(!msgList||!msgList->size())
        return;
    const Message& lastMsg =  msgList->back();
    //3.定义要显示的内容
    QString text;
    switch(lastMsg.messageType)
    {
        case MessageType::TEXT_TYPE:
        {
            text = lastMsg.content;
            break;
        }
        case MessageType::IMAGE_TYPE:
        {
            text = "[图片]";
            break;
        }
        case MessageType::SPEECH_TYPE:
        {
            text = "[语音]";
            break;
        }
        case MessageType::FILE_TYPE:
        {
            text = "[文件]";
            break;
        }
        default:
        {
            LOG()<<"错误的消息类型,MessageType="<<(int)lastMsg.messageType;
        }
    }
    if(sessionId==dataCenter->getCurrentSessionId())
        messageLabel->setText(text);
    else
    {
        int unreadCount = dataCenter->getUnread(sessionId);
        if(unreadCount>0)
            messageLabel->setText(QString("[未读%1条]").arg(unreadCount)+text);
    }

}
///////////////////////////////////////////////////////////////
/// 好友Item
///////////////////////////////////////////////////////////////
friendItem::friendItem(QWidget* owner,const QString& userId,const QIcon& avatar,const QString& name)
    :sessionFriendItem(owner,avatar,name),userId(userId)
{
}
void friendItem::active()
{
    LOG()<<"好友被点击触发的逻辑，userId="<<userId;
}


///////////////////////////////////////////////////////////////
/// 申请Item
///////////////////////////////////////////////////////////////

applyItem::applyItem(QWidget* owner,const QString& userId,const QIcon& avatar,const QString& name)
    :sessionFriendItem(owner,avatar,name),userId(userId)
{

    QPushButton* yesBtn = new QPushButton;
    yesBtn->setText("同意");
    QPushButton* noBtn = new QPushButton;
    noBtn->setText("拒绝");

    dynamic_cast<QGridLayout*>(this->layout())->addWidget(yesBtn,1,2,1,1);
    dynamic_cast<QGridLayout*>(this->layout())->addWidget(noBtn,1,3,1,1);

    connect(yesBtn,&QPushButton::clicked,this,&applyItem::clickYesApply);
    connect(noBtn,&QPushButton::clicked,this,&applyItem::clickNoApply);

}
void applyItem::active()
{
    LOG()<<"申请被点击触发的逻辑，userId="<<userId;
}
void applyItem::clickYesApply()
{
    LOG()<<"同意申请被点击触发的逻辑，userId="<<userId;
    model::DataCenter* dataCenter = model::DataCenter::getInstance();
    dataCenter->processFriendApplyAsync(true,userId);
}
void applyItem::clickNoApply()
{
    LOG()<<"拒绝申请被点击触发的逻辑，userId="<<userId;
    model::DataCenter* dataCenter = model::DataCenter::getInstance();
    dataCenter->processFriendApplyAsync(false,userId);
}
